package server

import (
	"context"
	"log"
	pb "proto"
)

type CrossServer struct {
	pb.UnimplementedCrossServiceServer
	matchMaker   *MatchMaker
	battleClient pb.BattleServiceClient
}

func NewCrossServer(battleClient pb.BattleServiceClient) *CrossServer {
	return &CrossServer{
		matchMaker:   NewMatchMaker(),
		battleClient: battleClient,
	}
}

// HandleCrossServerRequest 处理来自game-server的请求
func (s *CrossServer) HandleCrossServerRequest(ctx context.Context, req *pb.CrossServerRequest) (*pb.CrossServerResponse, error) {
	log.Printf("Received match request from player %s with %d heroes", req.PlayerId, len(req.Formation))

	// 开始匹配
	matchResult, err := s.matchMaker.StartMatch(req.PlayerId, req.Formation)
	if err != nil {
		return &pb.CrossServerResponse{
			Success: false,
			Message: "Match failed: " + err.Error(),
		}, nil
	}

	// 创建战斗请求
	var positions []*pb.Position
	for _, item := range req.Formation {
		position := pb.Position{
			HeroId:   item.HeroId,
			Position: item.Position,
		}
		positions = append(positions, &position)
	}

	var matchPositions []*pb.Position
	for _, item := range matchResult.OpponentFormation {
		position := pb.Position{
			HeroId:   item.HeroId,
			Position: item.Position,
		}
		matchPositions = append(matchPositions, &position)

	}

	battleReq := &pb.BattleRequest{
		Player1: &pb.Player{
			PlayerId:  req.PlayerId,
			Formation: positions,
		},
		Player2: &pb.Player{
			PlayerId:  matchResult.OpponentID,
			Formation: matchPositions,
		},
	}

	// 调用battle-server开始战斗
	battleResp, err := s.battleClient.StartBattle(ctx, battleReq)
	if err != nil {
		return &pb.CrossServerResponse{
			Success: false,
			Message: "Failed to start battle: " + err.Error(),
		}, nil
	}

	return &pb.CrossServerResponse{
		Success: true,
		Message: "Battle started",
		Data:    []byte(battleResp.BattleId),
	}, nil
}
